<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link href="css/bootstrap.css" rel="stylesheet">
    <script src="./lib/vue.js"></script>
</head>

<body>
    <div id="app">
        <cmt-box @func='loadComments()'>

        </cmt-box>

        <ul class="list-group">
            <li class="list-group-item" v-for="item in list" :key="item.id">
                <span class="badge">评论人：{{item.name}}</span>
                {{item.content}}
            </li>
        </ul>
    </div>

    <template id="tmp1">
        <div>
            <div class="form-group">
                <label>评论人：</label>
                <input type="text" class="form-control" v-model="user">
            </div>

            <div class="form-group">
                <label>内容：</label>
                <textarea type="text" class="form-control" v-model="content"></textarea>
            </div>

            <input type="button" value="发表评论" class="btn btn-primary" @click="commitContent">

        </div>
    </template>
</body>
<script>

    var commentBox = {
        template: "#tmp1",
        data() {
            return {
                user: '',
                content: ''
            };
        },
        methods: {
            commitContent() {
                var comment = { id: Date.now(), name: this.user, content: this.content };
                var list = JSON.parse(localStorage.getItem('cmts') || '[]');
                list.unshift(comment);
                localStorage.setItem('cmts', JSON.stringify(list));
                this.user = this.content = '';
                this.$emit('func');
            }
        }

    }

    var vm = new Vue({
        el: "#app",
        data: {
            list: [
                { id: Date.now(), name: "大毛", content: "大毛的评论" },
                { id: Date.now() + 1, name: "二毛", content: "二毛的评论" },
                { id: Date.now() + 2, name: "三毛", content: "三毛的评论" }
            ]
        },
        methods: {
            loadComments(){
                var list = JSON.parse(localStorage.getItem('cmts') || '[]');
                this.list = list;
            }
        },
        created: function(){
            this.loadComments();
        },
        components: {
            'cmt-box': commentBox
        }
    });
</script>

</html>